from lime.lime_tabular import LimeTabularExplainer
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
def Lime_instance(train_df,test_df,instance_index,rf,csv_pic_file=False):
    X_train = train_df.iloc[:, 2:]
    X_test = test_df.iloc[:, 2:]
    test_df.to_csv('test_df.csv', index=True)
    feature_names = list(X_train.columns)
    explainer = LimeTabularExplainer(X_train.values, feature_names=feature_names, class_names=['0', '1'], discretize_continuous=True)

    # 选择特定的测试实例
    instance_index = 0
    # 获取对应的真实类别
    y_true,y_special = test_df.iloc[instance_index, [1,0]]
    # print(f"True label: {y_true}")
    # print(f"Special label: {y_special}")

    # 获取预测概率
    y_pred_proba = rf.predict_proba(X_test)[instance_index]
    # print(f"Predicted probability: {y_pred_proba}")
    # 获取预测类别
    y_pred_class = y_pred_proba.argmax()
    # print(f"Predicted class: {y_pred_class}")
    # Lime解释
    exp = explainer.explain_instance(X_test.values[instance_index], rf.predict_proba, num_features=7)
    exp.show_in_notebook(show_table=True, show_all=True)
    if csv_pic_file is not False:
        # 获取特征及其重要性
        explanation_list = exp.as_list()  # 获取特征及其重要性
        explanation_df = pd.DataFrame(explanation_list, columns=['Feature', 'Importance'])  # 转换为 DataFrame


        # 准备其他列并填充 NaN 仅在你有数据时
        index_value = [instance_index] * len(explanation_df)  # 与特征数量相同的索引列表
        true_class_value = [y_true] * len(explanation_df)      # 真实类别
        special_class_value = [y_special] * len(explanation_df) # 特殊类别
        predicted_proba_value = [y_pred_proba] * len(explanation_df)  # 预测概率
        predicted_class_value = [y_pred_class] * len(explanation_df)   # 预测分类

        # 如果其他列较短，可以填充空值
        instance_df = pd.DataFrame({
            'Index': index_value,
            'True_Class': true_class_value,
            'Special_Class': special_class_value,
            'Predicted_Probability': predicted_proba_value,
            'Predicted_Class': predicted_class_value,
            'Feature': explanation_df['Feature'],
            'Importance': explanation_df['Importance']
        })
        instance_df.loc[1:, ['Index', 'True_Class', 'Special_Class', 'Predicted_Probability', 'Predicted_Class']] = np.nan
        # 分别保存为csv文件和xlsx文件
        dir = f'./instance/sample_{instance_index}'

        instance_csv_file = os.path.join(dir, f'instance_df_{instance_index}.csv')
        if not os.path.exists(dir):
            os.makedirs(dir)
        instance_df.to_csv(instance_csv_file, index=False)  # 以不带索引的形式保存

        fig_instance = exp.as_pyplot_figure()
        fig_instance.savefig(os.path.join(dir, f'lime_explanation_{instance_index}.png'))  # 保存为 PNG 文件
        plt.close(fig_instance)  # 关闭图像以释放内存